<template>
  <div class="pt-24px">
    <!-- model字段: Object 存放表单中数据的对象容器 -->
    <n-form size="large" :show-label="false" ref="formRef" :model="model" :rules="rules">
      <n-form-item path="phone">
        <n-input v-model:value="model.phone" placeholder="手机号码"></n-input>
      </n-form-item>
      <n-form-item path="code">
        <n-input v-model:value="model.code" placeholder="验证码"></n-input>
        <div class="w-18px"></div>
        <n-button size="large" :disabled="isCounting" @click="handleSmsCode">{{ label }}</n-button>
      </n-form-item>
      <n-space :vertical="true" size="large">
        <n-button type="primary" size="large" :block="true" :round="true" @click="handleSubmit">
          确定
        </n-button>
        <n-button size="large" :block="true" :round="true" @click="toLogin('pwd-login')">
          返回
        </n-button>
      </n-space>
    </n-form>
  </div>
</template>

<script setup lang="ts">
import type { FormInst } from 'naive-ui'
import { useMessage } from 'naive-ui'
import { reactive, ref } from 'vue'
import { useSmsCode, useRouterChange } from '@/hooks'

const model = reactive({
  phone: '',
  code: '',
})
const rules = {
  phone: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请输入手机号',
  },
  code: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请输入验证码',
  },
}
const { start, label, isCounting } = useSmsCode()
const { toLogin } = useRouterChange()
// 变量名必须与 template 对象的 ref 属性值相同
const formRef = ref<(HTMLElement & FormInst) | null>(null)
const message = useMessage()

function handleSmsCode() {
  // todo: 添加发送获取手机验证码的 ajax 请求
  start()
}

function handleSubmit(e: MouseEvent) {
  // todo: 目前只实现对手机号与验证码的非空校验，未发送请求到后端
  // validate 只是根据 rules 进行规则校验
  formRef.value?.validate((errors) => {
    if (!errors) {
      message.success('验证成功')
    } else {
      message.error('验证失败' + errors)
    }
  })
}
</script>

<style scoped></style>
